package com.yuanqi.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expirationMs;

    private Key signingKey;

    @PostConstruct
    public void init() {
        byte[] keyBytes;
        try {
            if (secret != null && secret.startsWith("base64:")) {
                // 仅当显式声明 base64: 前缀时才进行 Base64 解码
                String base64 = secret.substring("base64:".length());
                keyBytes = java.util.Base64.getDecoder().decode(base64);
            } else {
                keyBytes = secret.getBytes(StandardCharsets.UTF_8);
            }
            // JJWT 要求 HS256 秘钥长度至少 256 bit。若不足，使用 SHA-256 扩展为 32 字节
            if (keyBytes.length < 32) {
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                keyBytes = md.digest(keyBytes);
            }
            this.signingKey = Keys.hmacShaKeyFor(keyBytes);
        } catch (Exception e) {
            throw new IllegalStateException("初始化JWT密钥失败: " + e.getMessage(), e);
        }
    }

    public String generateToken(String subject, Map<String, Object> claims) {
        long now = System.currentTimeMillis();
        Date issuedAt = new Date(now);
        Date expiry = new Date(now + expirationMs);
        Map<String, Object> payload = new HashMap<>(claims == null ? new HashMap<>() : claims);
        return Jwts.builder()
                .setSubject(subject)
                .addClaims(payload)
                .setIssuedAt(issuedAt)
                .setExpiration(expiry)
                .signWith(signingKey, SignatureAlgorithm.HS256)
                .compact();
    }
}


